package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/*
* 该线程任务负责与指定的客户端进行HTTP交互
* HTTP协议要求浏览器与服务端采取“一问一答”的模式。对此，这里的处理流程分为三步：
* 1.解析请求
* 2.处理请求
* 3.发送请求
* */
public class ClientHandler implements Runnable {
    private Socket socket;
    //ClientHandler new的时候执行构造函数 复制给线程的属性，run方法就可以用了，传参的小方法
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            /*
            * 1. 解析请求
            *
            * */
            HttpServletRequest request = new HttpServletRequest(socket);


            //2.处理请求
            //获取请求的抽象路径
            String path = request.getUrl();
            System.out.println(path);
            //定位当前项目的类加载路径
            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            //定位类加载路径下的static目录
            File staticDir = new File(baseDir,"static");
            /*
            * File定位static下的用户请求的资源可能不存在或者定位的是一个目录
            * 这都属于失效的情况
            * 例如：
            * http://localhost:8088/123.html   static下没有123.html
            * http://localhost:8088/           定位的就是static目录本身
            * 上述两种情况都应当响应404
            * */
            File file = new File(staticDir,path);
            int statusCode;
            String statusReason;
            if (file.isFile()){
                statusCode = 200;
                statusReason = "OK";
            }else {
                statusCode = 404;
                statusReason = "NotFound";
                file = new File(staticDir,"404.html");
            }
            //3. 发送响应
            //3.1 发送状态行
            println("HTTP/1.1" + " " + statusCode + " " + statusReason);
            //3.2 发送响应头
            println("Content-Type: text/html");
            println("Content-length: "+file.length());
            //单独发送回车换行 表示响应头发送完毕
            println("");
            //3.3 发送响应正文
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] buf = new byte[1024*10];
            int d;
            while ((d=fis.read(buf))!=-1){
                out.write(buf,0,d);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    /*向客户发送一行字符串*/
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte data[] = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }
    public static void main(String[] args) {

    }
}
